package com.adjy.pathbuilders.screens;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;

import com.adjy.pathbuilders.R;
import com.adjy.pathbuilders.commons.FontLoader;
import com.adjy.pathbuilders.commons.Util;
import com.adjy.pathbuilders.objects.button.Button;
import com.adjy.pathbuilders.objects.button.ImageButton;
import com.adjy.pathbuilders.objects.button.TextImageButton;
import com.adjy.pathbuilders.objects.button.listeners.BackToMainMenuButtonListener;
import com.adjy.pathbuilders.objects.button.listeners.ButtonListener;
import com.adjy.pathbuilders.objects.button.listeners.MutableButtonListener;
import com.adjy.pathbuilders.profile.Player;
import com.adjy.pathbuilders.rendering.DisplayConverter;
import com.adjy.pathbuilders.rendering.GameCanvas;
import com.adjy.pathbuilders.rendering.loading.AnimationFactory;
import com.adjy.pathbuilders.rendering.loading.WeakReferenceBitmap;
import com.adjy.pathbuilders.screens.content.CustomDialog;
import com.adjy.pathbuilders.social.FacebookConnect;
import com.adjy.pathbuilders.state.Game;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;

public class FacebookConnectScreen implements GameScreen, OnClickListener {
	private Game game;
	private AnimationFactory anFactory;
	private List<Button> buttons;
	private Paint paint;
	private MutableButtonListener logInOutListener;
	private Player player;
	private Bitmap defaultPicture;
	
	public FacebookConnectScreen(AnimationFactory factory, Game game) {
		this.anFactory = factory;
		this.game = game;
		this.player = this.game.getPlayer();
		
		ProfilePictureView profilePictureFB = new ProfilePictureView(game.getContext());
		profilePictureFB.setProfileId(null);
		
		Bitmap auxBitmap = Util.getBitmapFromView(profilePictureFB);
		
		this.defaultPicture = Bitmap.createScaledBitmap(auxBitmap, (int)DisplayConverter.getScreenRatioHeight()*100, (int)DisplayConverter.getScreenRatioWidth()*100, true);
		auxBitmap.recycle();
		
		this.player.setPicture(defaultPicture);
		
		this.buttons = new ArrayList<Button>();
		
		this.paint = new Paint();
		this.paint.setColor(Color.BLACK);
		this.paint.setTextSize(FontLoader.getInstance().getFontSize() / 3);
		this.paint.setAntiAlias(true);
		this.paint.setFakeBoldText(true);
	}
	
	private void createButtons() {
		ImageButton logInOrLogOutButton = getLogInOrLogOutButton();
		
		buttons.add(logInOrLogOutButton);
		
		buttons.add(new TextImageButton(
				200, 380,
				new BackToMainMenuButtonListener(game),
				new WeakReferenceBitmap(anFactory, "menu_button_selected"),
				new WeakReferenceBitmap(anFactory, "menu_button_unselected"),
				game.getContext().getString(R.string.back)));
		
		buttons.add(new TextImageButton(
				200, 280,
				new ButtonListener() {
					
					@Override
					public void onButtonPressed() {
						View.OnClickListener confirmOnClickListener = new View.OnClickListener() {
				            public void onClick(View v) {
				            	CustomDialog dialog = CustomDialog.getInstance();
				            	FacebookConnectScreen.this.post(dialog.getInput());
				            	dialog.getDialog().dismiss();
				            }
				        };
				        CustomDialog.getInstance().createDialog(game.getContext().getString(R.string.share_friends),
				        		game.getContext().getString(R.string.fb_say_felling),
				        		game.getContext().getString(R.string.fb_having_fun),
				        		confirmOnClickListener , null);
					}
				},
				new WeakReferenceBitmap(anFactory, "menu_button_selected"),
				new WeakReferenceBitmap(anFactory, "menu_button_unselected"),
				game.getContext().getString(R.string.share)));
	}

	/**
	 * Creates a button that can logIn or LogOut (depends if there's already an active session.
	 * 
	 * @return
	 */
	private ImageButton getLogInOrLogOutButton() {
		WeakReferenceBitmap us1 = new WeakReferenceBitmap(anFactory, "fb_login");
		WeakReferenceBitmap s1 = new WeakReferenceBitmap(anFactory, "fb_login_down");
		
		WeakReferenceBitmap us2 = new WeakReferenceBitmap(anFactory, "fb_logout");
		WeakReferenceBitmap s2 = new WeakReferenceBitmap(anFactory, "fb_logout_down");
		
		this.logInOutListener = new MutableButtonListener(s1, us1, s2, us2) {
	
			@Override
			public void onButtonPressed1() {
				FacebookConnect.getInstance().fbLogIn();
				if(FacebookConnectScreen.this.game.getFacebookUser() != null) {
					setState(2);
				} else {
					setState(1);
				}
			}
	
			@Override
			public void onButtonPressed2() {
				FacebookConnect.getInstance().fbLogOut();
				if(FacebookConnectScreen.this.game.getFacebookUser() != null) {
					setState(2);
				} else {
					setState(1);
				}
			}
		};
		
		ImageButton imageButton = new ImageButton(200, 180,	logInOutListener,	s1,	us1);
		
		this.logInOutListener.setButton(imageButton);
		return imageButton;
	}
	
	@Override
	public void load() {
		anFactory.loadImages("logo", "main_menu_bg",
				"fb_pic", "fb_login", "fb_login_down", "fb_logout", "fb_logout_down", "marketing_mainMenu", "marketing_record");
		createButtons();
	}

	@Override
	public void release() {
		anFactory.releaseImages("logo", "main_menu_bg", "fb_pic", "fb_login", "fb_login_down", "fb_logout", "fb_logout_down", "marketing_mainMenu", "marketing_record");
		this.buttons.clear();
	}

	@Override
	public void render(GameCanvas mcanvas, float timeElapsed) {
		mcanvas.drawBackground(anFactory.getImage("main_menu_bg"));
		mcanvas.drawBitmapWithConversion(anFactory.getImage("logo"), 185, 20);
		
		mcanvas.drawBitmapWithConversion(this.player.getPicture(), 0, 60);
		
		if(this.player.getFullName().isEmpty()){
			mcanvas.drawText(game.getContext().getString(R.string.fb_login), 50, 50, this.paint);
		} else {
			mcanvas.drawText(this.player.getFullName(), 50, 50, this.paint);
		}
		
		for (Button b : buttons) {
			b.render(mcanvas, timeElapsed);
		}
	}

	@Override
	public void step(float timePassed) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void input(MotionEvent event) {
		for (Button b : buttons) {
			b.input(event);
		}
	}
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
	}
	
	public void fbLoginListener() {
		if(this.game.getFacebookUser() != null) {
			this.logInOutListener.setState(2);
		} else {
			this.logInOutListener.setState(1);
		}
		updateProfile();
	}

	private void updateProfile() {
		if(this.game.getFacebookUser() != null) {
			GraphUser fbUser = this.game.getFacebookUser();
			this.player.setFirstName(fbUser.getFirstName());
			this.player.setLastName(fbUser.getLastName());
			this.player.setMiddleName(fbUser.getMiddleName());
			new DownloadImageTask(this.defaultPicture.getWidth(), this.defaultPicture.getHeight()).execute(new String [] {this.game.getFacebookUser().getId()});
		}
	}

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

		private int width;
		private int height;

		public DownloadImageTask(int height, int width) {
			this.width = width;
			this.height = height;
		}
		
		@Override
		protected Bitmap doInBackground(String... params) {
			InputStream is = null;
			try {
				is = (InputStream)new URL("https://graph.facebook.com/" + params[0] + "/picture?width="+ this.width + "&height="+ this.height).getContent();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return BitmapFactory.decodeStream(is);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			FacebookConnectScreen.this.player.setPicture(result);
		}
	}
	
	private void post() {
		post(game.getContext().getString(R.string.fb_post));
	}
	
	private void post(String input) {
		this.post(this.anFactory.getImage("marketing_mainMenu"), input);
	}
	
	private void post(Bitmap bitmap, String description){
		if(bitmap != null && description != null)
		FacebookConnect.getInstance().fbPostPhoto(bitmap, description);
	}
	
	public void actionListener(String string) {
		this.post(this.anFactory.getImage("marketing_record"), string);
	}
	
}